package info.fqtech.app.yzjn.yuanlizixun;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import info.fqtech.app.yzjn.yingzaijinniuapp.R;

public class MainActivity extends AppCompatActivity {


    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

    String cookies = "";
    // 获取组件
    WebView webView;
    // 加载的地址
    String url;

    RelativeLayout navBar;

    TextView backTextView;

    TextView titleTextView;
    // 表示url地址是否为自己的站点
    String urlKey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 设置全屏
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        // 获取组件
        webView = findViewById(R.id.AppWebView);
        backTextView = findViewById(R.id.navBackBtn);
        titleTextView = findViewById(R.id.navTitle);
        navBar = findViewById(R.id.navBar);

        urlKey = getResources().getString(R.string.urlKey);
        // 设置参数
        //setWebViewConfig(webView);
        // 获取访问地址
        url = getResources().getString(R.string.load_url);
        // 获取cookie实例对象
        CookieManager cookieManager = CookieManager.getInstance();
        // 设置接受cookie
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(url, cookies);

        backTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(webView.canGoBack()){
                    setNavBarShow();
                    webView.goBack();
                }
            }
        });

        // 初始化
        initWebView();

    }

    /**
     * 设置webView的参数
     */
    @SuppressLint("SetJavaScriptEnabled")
    protected void initWebView() {
        WebClient webChromeClient = new WebClient();
        WebClientBase webViewClient = new WebClientBase();
        WebSettings webSettings = webView.getSettings();
        //设置js支持
        webSettings.setJavaScriptEnabled(true);
        // 设置支持javascript脚本
        webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
        //设置缓存
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setUseWideViewPort(true);//关键点
        webSettings.setLoadWithOverviewMode(true);//全屏
        webSettings.setBuiltInZoomControls(true);// 设置显示缩放按钮
        webSettings.setSupportZoom(true);//支持缩放
        webSettings.setDisplayZoomControls(false);
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        webView.setDrawingCacheEnabled(true);
        webView.getSettings().setBlockNetworkImage(true);
        webView.setWebViewClient(webViewClient);
        webView.requestFocus(View.FOCUS_DOWN);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        webView.setWebChromeClient(webChromeClient);


        webView.setWebChromeClient(new WebChromeClient() {

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });

        // 隐藏导航条
        navBar.setVisibility(View.GONE);
        // 设置WebView加载地址
        webView.loadUrl(url);
    }

    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "选择图片"), FILE_CHOOSER_RESULT_CODE);
    }

    /**
     * 显示或隐藏导航条
     */
    private void setNavBarShow(){
        if(!this.url.contains(urlKey)){
            navBar.setVisibility(View.VISIBLE);
        }else {
            navBar.setVisibility(View.GONE);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            setNavBarShow();
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    class WebClient extends WebChromeClient {
        public WebClient() {
            super();
        }

        @Override
        public void onProgressChanged(WebView webView, int i) {
            webView.getSettings().setBlockNetworkImage(false);
            super.onProgressChanged(webView, i);
        }
    }

    @Override
    protected void onDestroy() {
        webView.destroy();
        super.onDestroy();
    }

    class WebClientBase extends WebViewClient {



        @Override
        public void onPageStarted(WebView webView, String url, Bitmap bitmap) {
            // 设置主地址
            MainActivity.this.url = url;
            // 监听页面url地址的变化，如果是第三方的url，则显示导航条
            setNavBarShow();
            super.onPageStarted(webView, url, bitmap);
        }

        @Override
        public void onPageFinished(WebView webView, String s) {
            super.onPageFinished(webView, s);
            webView.getSettings().setBlockNetworkImage(false);
            int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            webView.measure(w, h);
        }

        @Override
        public void onReceivedError(WebView webView, int i, String s, String s1) {
            super.onReceivedError(webView, i, s, s1);
            String errorHtml = "<html><body><h2>系统维护中，请稍后再打开</h2></body></html>";
            webView.loadDataWithBaseURL(null, errorHtml, "text/html", "UTF-8", null);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

}
